import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/text_tag_list.dart';
import 'package:cbec_app/components/goods/goods_add_minus.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

///选择规格
class SelectSpecificationsPopup extends StatefulWidget {
  ///商品信息
  final Map<String, dynamic> goodsInfo;

  ///点击确定按钮回调
  final Function(int specIndex, int goodsNum, int? groupIndex)? onConfirm;

  ///已选商品数量
  final int goodsNum;

  ///商品类型 0-普通商品 1-特价商品 2-拼团商品 3-秒杀商品 4-砍价商品 5-预售商品
  final int goodsType;

  ///商品价格(手动传入将不使用商品详情进行取值)
  final String? price;

  ///商品划线价(手动传入将不使用商品详情进行取值)
  final String? priceMarket;

  ///商品主图(手动传入将不使用商品详情进行取值)
  final String? mainImg;

  ///切换规格回调
  final Function(String id)? onSelectSku;

  ///选中的规格索引
  final int? selectedIndex;

  ///是否显示拼团
  final bool isShowGroup;

  ///选中的拼团索引
  final int? selectedGroupIndex;

  final String? specValue;

  const SelectSpecificationsPopup({
    super.key,
    this.onConfirm,
    this.goodsNum = 1,
    this.price,
    this.priceMarket,
    this.mainImg,
    this.onSelectSku,
    this.selectedIndex = 0,
    this.goodsType = 0,
    required this.goodsInfo,
    this.isShowGroup = false,
    this.selectedGroupIndex = 0,
    this.specValue,
  });

  @override
  State<StatefulWidget> createState() {
    return _SelectSpecificationsPopupState();
  }
}

class _SelectSpecificationsPopupState extends State<SelectSpecificationsPopup> {
  ///默认选中的索引列表
  List<int> defaultIndexList = [];

  ///商品信息
  Map<String, dynamic> _goodsInfo = {};

  int _goodsType = 0;

  ///保存当前选中的skuId
  String prevSkuId = '';

  ///已选商品数量
  int selectedGoodsNum = 1;

  int curIndex = 0;

  int curGroupIndex = 0;

  @override
  void initState() {
    super.initState();
    _goodsInfo = widget.goodsInfo;
    _goodsType = widget.goodsType;
    curIndex = widget.selectedIndex!;
    curGroupIndex = widget.selectedGroupIndex!;
    selectedGoodsNum = widget.goodsNum;

    EventMgr.on(EventType.refreshSkuPopup, (arg) {
      //print('刷新走了没？$arg');
      setState(() {
        if (arg is int) {
          _goodsType = arg;
        } else {
          _goodsInfo = arg;
        }

        selectedGoodsNum = 1;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    EventMgr.off(EventType.refreshSkuPopup);
  }

  ///获取规格属性列表
  ///           // e.g.
  ///              {
  //                "pid": "1826822288519000066",
  //                "specName": "蔬菜大小",
  //                "specValues": [
  //                  {
  //                    "vid": "1826822288997150722",
  //                    "valueName": "小捆"
  //                  },
  //                  {
  //                    "vid": "1826822289001345026",
  //                    "valueName": "中捆"
  //                  },
  //                  {
  //                    "vid": "1826822289005539330",
  //                    "valueName": "大捆"
  //                  }
  //                ]
  //              }
  List getPropList() {
    List arr = [];
    if (_goodsInfo['skuBase'] != null && _goodsInfo['skuBase']['props'] != null) {
      for (var item in _goodsInfo['skuBase']['props']) {
        arr.add(item);
      }
    }
    print('prop arr = $arr');
    return arr;
  }

  ///获取sku属性列表
  ///  e.g.
  /// {
  //      "skuId": "896059516686192718",
  //      "image": "https://indoorbuydev.oss-cn-hangzhou.aliyuncs.com/images/supplierimg/1724485532103_48ecaf19.jpg",
  //      "propPath": "1826822288519000066:1826822288997150722;1826822411219169282:1826822411244335106"
  //  }

  List getSkuList() {
    List arr = [];
    if (_goodsInfo['skuBase'] != null && _goodsInfo['skuBase']['skus'] != null) {
      arr = _goodsInfo['skuBase']['skus'];
    }
    print('sku arr = $arr');
    return arr;
  }

  ///获取规格属性列表
  ///             e.g.
  ///
  ///             {
  //              "specNum": 1,
  //              "price": 1.35,
  //              "priceActivity": null,
  //              "highPrice": 0.0,
  //              "priceMarket": 2.0,
  //              "priceTax": 0
  //            }

  List getSpecList() {
    List arr = [];
    if (_goodsInfo['specPriceList'] != null) {
      arr = _goodsInfo['specPriceList'];
    }

    return arr;
  }

  ///获取拼团列表
  List getGroupList() {
    List arr = [];
    if (_goodsInfo['bookInfo'] != null && _goodsInfo['bookInfo']['priceList'] != null) {
      arr = _goodsInfo['bookInfo']['priceList'];
    }

    return arr;
  }

  ///获取商品价格
  Map<String, dynamic> getPrice() {
    List arr = getSpecList();
    Map<String, dynamic> info = {};
    if (arr.length > curIndex) {
      info['priceMarket'] = arr[curIndex]['priceMarket'];
    } else {
      setState(() {
        curIndex = 0;
      });
      info['priceMarket'] = arr[curIndex]['priceMarket'];
    }

    // 0-普通订单 2-特价订单 3-秒杀订单 4-拼团订单 5-预售订单 6-卡券订单 7-充值订单 8-砍价订单 9-新人好礼订单

    // 预告不使用折扣价
    switch (_goodsType) {
      case 0:
        return arr[curIndex];
      case 2:
        bool isPreNotice = _goodsInfo['specialInfo']['status'] == 3;
        if (isPreNotice) {
          return arr[curIndex];
        } else {
          info['price'] = _goodsInfo['specialInfo']['priceSpecial'];
          return info;
        }
      case 3:
        bool isPreNotice = _goodsInfo['seckillInfo']['status'] == 3;
        if (isPreNotice) {
          return arr[curIndex];
        } else {
          info['price'] = _goodsInfo['seckillInfo']['priceSeckill'];
          return info;
        }
      case 4:
        bool isPreNotice = _goodsInfo['bookInfo']['status'] == 3;
        if (isPreNotice) {
          return arr[curIndex];
        } else {
          if (_goodsInfo['bookInfo']['hasSetMasterPrice'] == 1) {
            info['price'] = _goodsInfo['bookInfo']['priceBookMaster'];
          } else {
            print(' _goodsInfo  ====== ${_goodsInfo['bookInfo']}');
            List priceList = _goodsInfo['bookInfo']['priceList'];
            Map<dynamic, dynamic> item = priceList.first;
            info['price'] = item['priceBook'];
          }
          return info;
        }
      case 5:
        bool isPreNotice = _goodsInfo['preSaleInfo']['status'] == 3;
        if (isPreNotice) {
          return arr[curIndex];
        } else {
          info['price'] = _goodsInfo['preSaleInfo']['pricePresale'];
          return info;
        }
      case 8:
        info['price'] = _goodsInfo['haggleInfo']['priceHaggle'];
        return info;
      case 9:
        info['price'] = _goodsInfo['newUserInfo']['priceNewUser'];
        return info;
      case 6:
      case 7:
      default:
        return arr[curIndex];
    }
  }

  ///获取商品规格图片
  String getImgUrl() {
    String url = 'empty_default.png';
    for (var item in getSkuList()) {
      if (_goodsInfo['commodityId'] == item['skuId']) {
        url = item['image'];
        break;
      }
    }
    return url;
  }

// /goods-center/frontend/storeCommodity/query/detail/896059516686192717,参数{sid: 1842464344375885826, type: 0}
// /goods-center/frontend/storeCommodity/query/detail/896059516686192715,参数{sid: 1842464344375885826, type: 0}
  ///获取商品库存
  int getGoodsStock() {
    return _goodsInfo['number'] as int;
  }

  /// 选择的规格 字符串
  String selectedSpuSpecJsonBody() {
    if (_goodsInfo['spuSpecJsonBody'] == null) {
      return '';
    } else {
      return '规格:${_goodsInfo['spuSpecJsonBody']}';
    }
  }

  @override
  Widget build(BuildContext context) {
    // 获取屏幕高度
    double screenHeight = MediaQuery.of(context).size.height;

    // 计算最大高度为屏幕的 80%
    double maxHeight = screenHeight * 0.8;

    return Container(
      // 外部容器，设置了顶部圆角
      decoration: const BoxDecoration(color: Colors.white, borderRadius: BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8))),
      child: Container(
        // 使用 ConstrainedBox 来限制最大高度
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxHeight: maxHeight, // 最大高度设置为屏幕的80%
          ),
          child: SingleChildScrollView(
            // 使用 ScrollView 以便内容过多时可以滚动
            child: Padding(
              padding: EdgeInsets.only(top: 18.h, left: 18.w, right: 18.w),
              child: Stack(
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildTopWidget(),
                      TextTagList(
                        propsList: getPropList(),
                        skuList: getSkuList(),
                        specList: getSpecList(),
                        specIds: _goodsInfo['specValue'] ?? '',
                        onPropsClick: widget.onSelectSku,
                        unit: _goodsInfo['uniteName'] ?? '',
                        selectedIndex: widget.selectedIndex,
                        groupList: getGroupList(),
                        isShowGroup: widget.isShowGroup,
                        selectedGroupIndex: widget.selectedGroupIndex,
                        onSpecClick: (index) {
                          setState(() {
                            print('是不是这里');
                            curIndex = index;
                          });
                        },
                        onGroupClick: (index) {
                          print('是不是这里2');
                          setState(() {
                            curGroupIndex = index;
                          });
                        },
                      ),
                      // 这里包裹 _buildBottomNumWidget() 以确保它能显示
                      _buildBottomNumWidget(),

                      SizedBox(height: 50.0 + MediaQuery.of(context).padding.bottom),
                    ],
                  ),
                  Positioned(
                      bottom: MediaQuery.of(context).padding.bottom,
                      child: SizedBox(
                        height: 40,
                        child: solidButton('确定', () {
                          Get.back();
                          if (widget.onConfirm != null) {
                            widget.onConfirm!(curIndex, selectedGoodsNum, curGroupIndex);
                          }
                        }),
                      )),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 顶部组件
  Widget _buildTopWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            _goodsImg(radius: 0, left: 0),
            Container(
              width: ScreenUtil().screenWidth * 0.5,
              margin: EdgeInsets.only(left: 10.w),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  goodsSalesPrice(widget.price ?? getPrice()['price'].toString(), fontSize: 15),
                  Text(
                    '剩余库存:${getGoodsStock()}',
                    maxLines: 2, // 限制最多显示2行
                    overflow: TextOverflow.ellipsis, // 超出部分显示省略号
                    softWrap: true, // 允许换行
                    style: setTextStyle(12, FontWeight.normal, ThemeConfig.subTextColor),
                  ),
                  StatefulBuilder(
                    builder: (context, setState) {
                      return Text(
                        selectedSpuSpecJsonBody(),
                        style: setTextStyle(12, FontWeight.normal, ThemeConfig.subTextColor),
                      );
                    },
                  )
                ],
              ),
            )
          ],
        ),
        BaseInteractive(
          childWidget: Icon(
            Icons.close,
            color: Tools.fromHex('#333333'),
          ),
          onClick: () {
            Get.back();
          },
        )
      ],
    );
  }

  /// 底部数量加/减
  Widget _buildBottomNumWidget() {
    return Container(
      margin: EdgeInsets.only(top: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            '数量',
            style: setTextStyle(13, FontWeight.w400, ThemeConfig.mainTextColor),
          ),
          GoodsAddMinus(
            num: selectedGoodsNum,
            max: getGoodsStock(),
            onMinus: (goodsNum) {
              selectedGoodsNum = goodsNum;
            },
            onAdd: (goodsNum) {
              selectedGoodsNum = goodsNum;
            },
          )
        ],
      ),
    );
  }

  ///商品图片
  Widget _goodsImg({double radius = 12, double? left}) {
    print("widget.mainImg == ${widget.mainImg}");
    return Container(
      margin: EdgeInsets.only(left: left ?? 10.w),
      child: BaseImage(
        url: getImgUrl(),
        width: 100.w,
        height: 100.w,
        borderRadius: BorderRadius.all(Radius.circular(radius)),
      ),
    );
  }
}

///打开规格弹框
///goodsInfo 商品信息
///selectedList 已选规格列表,可不传
///onConfirm 确定选择的规格
///onSelectSku 切换规格回调
void showSelectSpecificationsPopup({
  Function(int specIndex, int goodsNum, int? groupIndex)? onConfirm,
  Function(String id)? onSelectSku,
  int selectedIndex = 0,
  int goodsNum = 1,
  int goodsType = 0,
  String? price,
  String? priceMarket,
  String? mainImg,
  String? specValue,
  bool isShowGroup = false,
  int selectedGroupIndex = 0,
  required Map<String, dynamic> goodsInfo,
}) {
  showCupertinoModalPopup(
    context: Get.context!,
    builder: (context) {
      return StatefulBuilder(
        builder: (context, setState) {
          return SelectSpecificationsPopup(
            goodsInfo: goodsInfo,
            onConfirm: onConfirm,
            onSelectSku: onSelectSku,
            goodsNum: goodsNum,
            goodsType: goodsType,
            price: price,
            priceMarket: priceMarket,
            mainImg: mainImg,
            selectedIndex: selectedIndex,
            isShowGroup: isShowGroup,
            selectedGroupIndex: selectedGroupIndex,
            specValue: specValue,
          );
        },
      );
    },
  );
}
